package com.rzico.sbl.ui.member

import android.widget.CompoundButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberWarnBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.BillWorkerData
import com.rzico.sbl.viewmodel.MemberViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionIf
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getColorEx
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.goneValue
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class MemberWarnActivity : BaseActivity(R.layout.activity_member_warn) {

    private val mBinding by lazy { ActivityMemberWarnBinding.bind(getRootView()) }

    private var isEditMode = false

    override fun getViewModel() = get<MemberViewModel>()

    override fun initData() {
        initTitle(title = "水票提醒", name = "批量")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.apply {
            warnAll.setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.address_default_selector
            )

            listLayout.apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关会员信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            if (!isLoadingMore) {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<BillWorkerData>(R.layout.item_warn_list) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_warn_name, "${bean.name}  ${bean.mobile}")
                                text(R.id.item_warn_num, bean.num)
                                text(R.id.item_warn_adress, bean.address)
                                text(R.id.item_warn_visit, bean.last_visit_day)
                                text(R.id.item_warn_count, bean.visit)

                                visibility(
                                    R.id.item_warn_adress,
                                    goneValue { bean.address.isNullOrEmpty() }
                                )

                                with<ImageView>(R.id.item_warn_img) {
                                    it.loadCircleImage(bean.logo, R.mipmap.default_user)
                                }

                                with<ImageView>(R.id.item_warn_check) {
                                    it.isVisible = isEditMode
                                    it.setImageResource(
                                        if (bean.check) R.mipmap.login_yes_orange
                                        else R.mipmap.login_no
                                    )
                                }

                                with<TextView>(R.id.item_warn_num) {
                                    it.text = bean.num
                                    it.setTextColor(
                                        getColorEx(
                                            if (bean.num.intValue < 4) R.color.red
                                            else R.color.gray
                                        )
                                    )
                                }

                                clicked(R.id.item_warn_img) {
                                    startActivityEx<MemberDetailActivity>(
                                        "cardId" to bean.id,
                                        "memberId" to bean.member,
                                        "memberPhone" to bean.mobile
                                    )
                                }

                                clicked(R.id.item_warn_call) {
                                    bean.mobile.notEmpty {
                                        showBottomPhoneDialog(this)
                                    }
                                }

                                clicked {
                                    if (isEditMode) {
                                        bean.check = !bean.check
                                        notifyItemChanged(index)

                                        checkTextHint()
                                    } else {
                                        startActivityEx<MemberOfflineRecordActivity>(
                                            "cardId" to bean.id
                                        )
                                    }
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }

            tvRight?.oneClick { view ->
                view as TextView
                isEditMode = !isEditMode

                isEditMode
                    .apply {
                        view.text = conditionIf(this, "取消", "批量")
                        warnBottom.isVisible = this
                    }
                    .condition {
                        mList.forEach {
                            it as BillWorkerData
                            it.check = false
                        }

                        checkTextHint()
                    }

                mAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun initListener() {
        observe<String>("tickeModify") { updateList() }

        mBinding.apply {
            warnCancel.oneClick {
                mList.forEach {
                    it as BillWorkerData
                    it.check = false
                }

                mAdapter.notifyDataSetChanged()

                checkTextHint()
            }

            warnSure.oneClick {
                if (mList.none { (it as BillWorkerData).check }) {
                    showToast("请选择要提醒的会员")
                    return@oneClick
                }

                getViewModel()
                    .requestBind(
                        requestUrl = BaseUrl.mngPush,
                        params = arrayOf(
                            "type" to "1",
                            "ids" to mList
                                .filter { (it as BillWorkerData).check }
                                .joinToString(",") { (it as BillWorkerData).id }
                        )
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("提醒成功！")

                            isEditMode = false
                            tvRight?.text = "批量"
                            warnBottom.isVisible = isEditMode

                            mAdapter.notifyDataSetChanged()
                        }
                    )
            }
        }
    }

    /**
     * 水票提醒列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .warnList(
                page = index,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)

                    if (isEditMode) checkTextHint()
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

    private fun checkTextHint() {
        mBinding.apply {
            warnAll
                .apply {
                    setOnCheckedChangeListener(null)
                    isChecked =
                        mList.isNotEmpty() && mList.none { !(it as BillWorkerData).check }
                    setOnCheckedChangeListener(this@MemberWarnActivity)
                }

            warnSure.text = "提醒(${mList.count { (it as BillWorkerData).check }})"
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach { (it as BillWorkerData).check = isChecked }
        mAdapter.notifyDataSetChanged()

        checkTextHint()
    }

}